/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By www.gzchengguo.cn
* 注意：
* 本软件为www.gzchengguo.cn开发研制，未经购买不得商用
* 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
* 一经发现盗用、分享等行为，将追究法律责任，后果自负
*/
package link.chengguo.orangemall.modules.user.rest;


import cn.hutool.core.util.StrUtil;
import link.chengguo.orangemall.api.ApiResult;
import link.chengguo.orangemall.common.aop.NoRepeatSubmit;
import link.chengguo.orangemall.common.bean.LocalUser;
import link.chengguo.orangemall.common.interceptor.AuthCheck;
import link.chengguo.orangemall.constant.ShopConstants;
import link.chengguo.orangemall.enums.BillInfoEnum;
import link.chengguo.orangemall.modules.order.service.OrangeStoreOrderService;
import link.chengguo.orangemall.modules.order.vo.UserOrderCountVo;
import link.chengguo.orangemall.modules.product.service.OrangeStoreProductRelationService;
import link.chengguo.orangemall.modules.product.vo.OrangeStoreProductRelationQueryVo;
import link.chengguo.orangemall.modules.shop.service.OrangeSystemGroupDataService;
import link.chengguo.orangemall.modules.user.domain.OrangeUser;
import link.chengguo.orangemall.modules.user.param.UserEditParam;
import link.chengguo.orangemall.modules.user.service.OrangeUserBillService;
import link.chengguo.orangemall.modules.user.service.OrangeUserService;
import link.chengguo.orangemall.modules.user.service.OrangeUserSignService;
import link.chengguo.orangemall.modules.user.vo.SignVo;
import link.chengguo.orangemall.modules.user.vo.OrangeUserQueryVo;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import link.chengguo.orangemall.utils.RedisUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户控制器
 * </p>
 *
 * @author chengguo
 * @since 2019-10-16
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "用户中心", tags = "用户:用户中心", description = "用户中心")
public class UserController {

    private final OrangeUserService orangeUserService;
    private final OrangeSystemGroupDataService systemGroupDataService;
    private final OrangeStoreOrderService orderService;
    private final OrangeStoreProductRelationService relationService;
    private final OrangeUserSignService userSignService;
    private final OrangeUserBillService userBillService;
    private final RedisUtils redisUtil;



    /**
     * 用户资料
     */
    @AuthCheck
    @GetMapping("/userinfo")
    @ApiOperation(value = "获取用户信息",notes = "获取用户信息",response = OrangeUserQueryVo.class)
    public ApiResult<Object> userInfo(){
        OrangeUser orangeUser = LocalUser.getUser();
        return ApiResult.ok(orangeUserService.getNewOrangeUserById(orangeUser));
    }

    /**
     * 获取个人中心菜单
     */
    @GetMapping("/menu/user")
    @ApiOperation(value = "获取个人中心菜单",notes = "获取个人中心菜单")
    public ApiResult<Map<String,Object>> userMenu(){
        Map<String,Object> map = new LinkedHashMap<>();
        map.put("routine_my_menus",systemGroupDataService.getDatas(ShopConstants.ORANGEMALL_MY_MENUES));
        return ApiResult.ok(map);
    }



    /**
     * 订单统计数据
     */
    @AuthCheck
    @GetMapping("/order/data")
    @ApiOperation(value = "订单统计数据",notes = "订单统计数据")
    public ApiResult<UserOrderCountVo> orderData(){
        Long uid = LocalUser.getUser().getUid();
        return ApiResult.ok(orderService.orderData(uid));
    }

    /**
     * 获取收藏产品
     */
    @AuthCheck
    @GetMapping("/collect/user")
    @ApiOperation(value = "获取收藏产品",notes = "获取收藏产品")
    public ApiResult<List<OrangeStoreProductRelationQueryVo>> collectUser(@RequestParam(value = "page",defaultValue = "1") int page,
                                                                          @RequestParam(value = "limit",defaultValue = "10") int limit){
        Long uid = LocalUser.getUser().getUid();
        return ApiResult.ok(relationService.userCollectProduct(page,limit,uid));
    }

    /**
     * 用户资金统计
     */
    @AuthCheck
    @GetMapping("/user/balance")
    @ApiOperation(value = "用户资金统计",notes = "用户资金统计")
    public ApiResult<Object> userBalance(){
        OrangeUser orangeUser = LocalUser.getUser();
        Map<String,Object> map = Maps.newHashMap();
        Double[] userMoneys = orangeUserService.getUserMoney(orangeUser.getUid());
        map.put("now_money", orangeUser.getNowMoney());
        map.put("orderStatusSum",userMoneys[0]);
        map.put("recharge",userMoneys[1]);
        return ApiResult.ok(map);
    }


    /**
     * 签到用户信息
     */
    @AuthCheck
    @PostMapping("/sign/user")
    @ApiOperation(value = "签到用户信息",notes = "签到用户信息")
    public ApiResult<OrangeUserQueryVo> sign(){
        OrangeUser orangeUser = LocalUser.getUser();
        return ApiResult.ok(userSignService.userSignInfo(orangeUser));
    }

    /**
     * 签到配置
     */
    @GetMapping("/sign/config")
    @ApiOperation(value = "签到配置",notes = "签到配置")
    public ApiResult<Object> signConfig(){
        return ApiResult.ok(systemGroupDataService.getDatas(ShopConstants.ORANGEMALL_SIGN_DAY_NUM));
    }

    /**
     * 签到列表
     */
    @AuthCheck
    @GetMapping("/sign/list")
    @ApiOperation(value = "签到列表",notes = "签到列表")
    public ApiResult<List<SignVo>> signList(@RequestParam(value = "page",defaultValue = "1") int page,
                                            @RequestParam(value = "limit",defaultValue = "10") int limit){
        Long uid = LocalUser.getUser().getUid();
        return ApiResult.ok(userSignService.getSignList(uid,page,limit));
    }

    /**
     * 签到列表（年月）
     */
    @AuthCheck
    @GetMapping("/sign/month")
    @ApiOperation(value = "签到列表（年月）",notes = "签到列表（年月）")
    public ApiResult<Object> signMonthList(@RequestParam(value = "page",defaultValue = "1") int page,
                                           @RequestParam(value = "limit",defaultValue = "10") int limit){
        Long uid = LocalUser.getUser().getUid();
        return ApiResult.ok(userBillService.getUserBillList(page, limit,uid, BillInfoEnum.SIGN_INTEGRAL.getValue()));
    }

    /**
     * 开始签到
     */
    @NoRepeatSubmit
    @AuthCheck
    @PostMapping("/sign/integral")
    @ApiOperation(value = "开始签到",notes = "开始签到")
    public ApiResult<Object> signIntegral(){
        OrangeUser orangeUser = LocalUser.getUser();
        int integral = userSignService.sign(orangeUser);;

        Map<String,Object> map = new LinkedHashMap<>();
        map.put("integral",integral);
        return ApiResult.ok(map,"签到获得" + integral + "积分");
    }


    @AuthCheck
    @PostMapping("/user/edit")
    @ApiOperation(value = "用户修改信息",notes = "用修改信息")
    public ApiResult<Object> edit(@Validated @RequestBody UserEditParam param){
        OrangeUser orangeUser = LocalUser.getUser();
        orangeUser.setAvatar(param.getAvatar());
        orangeUser.setNickname(param.getNickname());
        orangeUser.setRealName(param.getRealName());
        orangeUser.setCardId(param.getCardId());
        orangeUser.setIdPhoto(param.getIdPhoto());
        orangeUser.setStoreName(param.getStoreName());
        orangeUser.setDistrictBelongTo(param.getDistrictBelongTo());
        orangeUser.setShopAdress(param.getShopAdress());
        orangeUser.setBusinessLicense(param.getBusinessLicense());
        orangeUser.setStorePhotos(param.getStorePhotos());
        orangeUserService.updateById(orangeUser);

        return ApiResult.ok("修改成功");
    }

    @AuthCheck
    @PostMapping("/user/editPhone/{phone}/{captcha}")
    @ApiOperation(value = "用户修改手机号码",notes = "用修改修改手机号码")
    public ApiResult<String> editPhone(@PathVariable String phone,@PathVariable String captcha){
        Object codeObj = redisUtil.get("code_" + phone);
        if(codeObj == null){
            return ApiResult.fail("请先获取验证码");
        }
        String code = codeObj.toString();
        if (!StrUtil.equals(code, captcha)) {
            return ApiResult.fail("验证码错误");
        }
        OrangeUser orangeUser = LocalUser.getUser();
        orangeUser.setPhone(phone);
        orangeUserService.updateById(orangeUser);

        return ApiResult.ok("修改成功");
    }




}

